﻿// See https://aka.ms/new-console-template for more information

//const string dir = @"D:\Downloads\Edge\COM3D2_Localisation\Script";

void ProcessTXTFile(string path) {
    Console.WriteLine(path);
    List<string> txt = new List<string>();
    using (var reader = new StreamReader(path)) {
        string? line;
        while ((line = reader.ReadLine()) != null) {
            if (line.IndexOf("<SC>") == -1) {
                txt.Add(line);
                continue;
            }
            if (line.IndexOf(@"@VoiceSubtitle") != -1) {
                string nl = line.Split("\"original\":\"")[1].Split("\",\"startTime\"")[0];
                string jsc = nl.Split("<TC>")[0];
                string jp = jsc.Split("<SC>")[0];
                string zh = jsc.Split("<SC>")[1];
                string prefix = line.Split("\"original\":\"")[0] + "\"original\":\"";
                string midfix = "\",\"startTime\"" + line.Split("\",\"startTime\"")[1].Split("\"translation\":\"")[0] + "\"translation\":\"";
                string postfix = "\",\"voice\"" + line.Split("\",\"voice\"")[1];
                txt.Add(prefix + jp + midfix + zh + postfix);
            } else {
                string jsc = line.Split("<TC>")[0];
                string jp = jsc.Split("<SC>")[0];
                string zh = jsc.Split("<SC>")[1];
                txt.Add(jp + "\t" + zh);
            }
        }
    }
    using (var writer = new StreamWriter(path)) {
        foreach (string line in txt) {
            writer.WriteLine(line);
        }
    }
}

void ProcessDirectory(string path) {
    Console.WriteLine("<" + path + ">");
    var txts = Directory.GetFiles(path, "*.txt");
    foreach (var file in txts) {
        ProcessTXTFile(file);
    }
    var paths = Directory.GetDirectories(path);
    foreach (var apath in paths) {
        ProcessDirectory(apath);
    }
}

if (args.Length == 0) {
    Console.WriteLine(@"请传入文件夹地址，可以是COM3D2_Localisation文件夹或Script文件夹");
    Console.WriteLine("路径如含有空格请使用引号括起来");
    Console.WriteLine("程序为源文件直接替换，请做好备份");
} else {
    string path = args[0];
    if (Directory.Exists(path)) {
        ProcessDirectory(path);
    } else {
        Console.WriteLine("文件夹\""+path+"\"不存在");
        Console.WriteLine("路径如含有空格请使用引号括起来");
    }
}



